'use client'

import { Swiper, SwiperSlide } from 'swiper/react'
import { Autoplay, Navigation } from 'swiper/modules'
import { Card, Tag } from 'antd'
import { LeftOutlined, RightOutlined } from '@ant-design/icons'

import 'swiper/css'
import 'swiper/css/navigation'
import styles from './index.module.css'
import './carousel.global.css'
import { useRef } from 'react'
import { useRouter } from 'next/navigation'

interface CarouselItem {
  id: string
  name: string
  type: string
  module: string
  description: string
  status: 'active' | 'inactive'
}

/**
 * Carousel 组件 props
 */
interface CarouselProps {
  items: CarouselItem[]
}
export default function Carousel({ items }: CarouselProps) {
  const prevRef = useRef<HTMLDivElement>(null)
  const nextRef = useRef<HTMLDivElement>(null)
  const router = useRouter(); // 初始化路由实例
  // 处理卡片点击跳转详情页
  const handleCardClick = (id: string) => {
    // 编程式路由跳转，路径可根据实际需求调整
    router.push(`/dashboard/${id}`);
  };
  return (
    <div className={styles.wrapper}>
      {/* 左箭头 */}
      <div className={`custom-prev`} ref={prevRef}>
        <LeftOutlined style={{ fontSize: 20 }} />
      </div>

      {/* Swiper 轮播 */}
      <Swiper
        slidesPerView={3}
        spaceBetween={24}
        loop
        navigation={{
          prevEl: prevRef.current,
          nextEl: nextRef.current,
        }}
        className={styles.swiper}
        modules={[Navigation, Autoplay]}
        autoplay={{ delay: 3000, disableOnInteraction: false }}
        onBeforeInit={(swiper) => {
          if (typeof window !== 'undefined') {
            // 绑定 navigation DOM 元素（重要！）
            // @ts-ignore
            swiper.params.navigation.prevEl = prevRef.current
            // @ts-ignore
            swiper.params.navigation.nextEl = nextRef.current
          }
        }}
      >
        {items?.map((item) => (
          <SwiperSlide key={item.id}>
            <Card
              title={<div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span>{item.name}</span>
                <Tag color={item.status === 'active' ? 'green' : 'red'}>
                  {item.status}
                </Tag>
              </div>}
              onClick={() => handleCardClick(item.id)} // 绑定点击事
            >
              <p><strong>类型：</strong>{item.type}</p>
              <p><strong>模块：</strong>{item.module}</p>
              <p><strong>描述：</strong>{item.description}</p>
            </Card>
          </SwiperSlide>
        ))}
      </Swiper>

      {/* 右箭头 */}
      <div className={`custom-next `} ref={nextRef}>
        <RightOutlined style={{ fontSize: 20 }} />
      </div>
    </div>
  )
}
